package com.javasm.boot.oauth2.config;

import com.javasm.boot.oauth2.entity.OauthUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
 * Author：MoDebing
 * Version：1.0
 * Date：2022-12-13-13:08
 * Description:
 */
@Configuration
public class TokenConfig {

    /**
     * token内容增强器
     *
     * @return
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
                Map<String, Object> info = new HashMap<>();
                OauthUser securityUser = (OauthUser) oAuth2Authentication.getPrincipal();
                info.put("id", securityUser.getId());

                // OAuth2AccessToken这是一个接口，要转成它的实现类才能调用set方法
                ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);

                return oAuth2AccessToken;
            }
        };
    }


    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        accessTokenConverter.setKeyPair(keyPair());
        return accessTokenConverter;
    }


    //Rsa秘钥

    /**
     * keytool -genkeypair -alias 123456 -keyalg RSA -keypass 123456 -keystore test.jks -storepass 123456
     * 生成rsa证书，-storepass oauth2 ，-storepass后面的oauth2是密码
     * <p>
     * -alias:密钥的别名
     * -keyalg:使用的hash算法
     * -keypass:密钥的访问密码
     * -keystore:密钥库文件名，oauth2.jks保存了生成的证书
     * -storepass:密钥库的访问密码
     *
     * @return
     */
    @Bean
    public KeyPair keyPair() {
        //从classpath下的证书中获取秘钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("test.jks"),
                "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("123456", "123456".toCharArray());
    }


}
